package Other;

import java.util.ArrayList;
import java.util.List;

import DataConnectionInterface.ConnectionPool;
import DataConnectionInterface.GameDataConnectionInterface;
import Helper.GameException;


public class UniverseListConcrete extends Pager implements UniverseList{

	private List<Universe> universes;
	
    public UniverseListConcrete(int entriesPerPage){
        initUniverseListConcrete(entriesPerPage);
    }

    private void initUniverseListConcrete(int entriesPerPage) {
    	init(entriesPerPage);
    }

    public int getNumOfUniverses() {
        return universes.size();
    }

    public Universe getUniverse(int index) {
        if(universes.size()>index) return universes.get(index);
        else return null;
    }

    public void removeUniverse(int index) {
    	ConnectionPool pool = null;
		GameDataConnectionInterface con = null;
		
    	int universeID = universes.get(index).getID();
    	try {
			pool = ConnectionPool.getInstance();
			con = pool.getConnection();
			con.deleteUniverse(universeID);
			RefreshPage(con);
			pool.returnConnection(con);
    	} catch (GameException e) {
    		if(pool != null && con != null)  pool.returnConnection(con);
    	}
    }

    public void addUniverse(Universe universe) {
    	ConnectionPool pool = null;
		GameDataConnectionInterface con = null;
    	try {
			pool = ConnectionPool.getInstance();
			con = pool.getConnection();
			con.addUniverse(universe.getName());
			RefreshPage(con);
			pool.returnConnection(con);
    	} catch (GameException e) {
    		if(pool != null && con != null)  pool.returnConnection(con);
    	}
    }

	// TODO: check boundaries
	protected void getNextPage(GameDataConnectionInterface con) throws GameException {
		
		List<Universe> tempList = con.getUniversePage(pageNumber + 1, entriesPerPage);
		if(tempList.size() == 0) return;
		universes = tempList;
		pageNumber++;
		}

	protected void getPreviousPage(GameDataConnectionInterface con) throws GameException {
		universes = con.getUniversePage(pageNumber -1, entriesPerPage);
		pageNumber--;
	}

	protected void RefreshPage(GameDataConnectionInterface con) throws GameException {
		universes = con.getUniversePage(pageNumber, entriesPerPage);
	}
}
